package com.ganzalang.gmall.designpatterns.composite;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 不使用组合模式
 * @author: ganzalang
 */
@Slf4j
public class WithoutCompositePatternDemo {

    public static void main(String[] args) {
        Department leafDept1 = new Department("叶子节点1-1");
        Department leafDept2 = new Department("叶子节点1-2");
        Department leafDept3 = new Department("叶子节点2-1");

        Department subDept1 = new Department("子节点1");
        subDept1.getChildren().add(leafDept1);
        subDept1.getChildren().add(leafDept2);

        Department subDept2 = new Department("子节点2");
        subDept2.getChildren().add(leafDept3);

        Department parentDept = new Department("父节点");
        parentDept.getChildren().add(subDept1);
        parentDept.getChildren().add(subDept2);


        for (Department child : parentDept.getChildren()) {
            if(child.getChildren().size() > 0){
                for (Department childChild : child.getChildren()) {
                    childChild.remove();
                }
            }
            child.remove();
        }
        parentDept.remove();

    }

    public static class Department {
        private String name;
        // 这里要实例化一个list，否则main中实例化的时候会报错
        private List<Department> children = new ArrayList<>();

        public Department(String name) {
            this.name = name;
        }

        public void setChildren(List<Department> children) {
            this.children = children;
        }

        public List<Department> getChildren() {
            return children;
        }

        public void remove() {
            log.info("删除节点" + name);
        }
    }
}
